package com.media.listener;

import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionBindingEvent;

@WebListener()
public class UserCountListener implements ServletContextListener,HttpSessionListener,HttpSessionAttributeListener
       {
           @Override
           public void sessionCreated (HttpSessionEvent se){
               ServletContext application = se.getSession().getServletContext();
               int userCount = (int) application.getAttribute("userCount");
               userCount ++;
               application.setAttribute("userCount",userCount);
               System.out.println("用户登录，系统当前在线人数：+userCount");
           }
           @Override
           public void sessionDestroyed(HttpSessionEvent se )
           {
               ServletContext application = se.getSession().getServletContext();
               int userCount = (int) application.getAttribute("userCount");
               if (userCount !=0){
                   userCount--;
               }else{
                   userCount =0;
               }
               application.setAttribute("userCount",userCount);
               System.out.println("用户注销，系统当前在线人数：+userCount");
           }
           @Override
           public void contextInitialized (ServletContextEvent sce)
           {
               ServletContext applicationn = sce.getServletContext();
               applicationn.setAttribute("userCount",0);
           }

           @Override
           public void attributeAdded(HttpSessionBindingEvent se) {
               System.out.println("session添加属性");

           }
           @Override
           public void attributeRemoved(HttpSessionBindingEvent se) {
           }
           @Override
           public void attributeReplaced(HttpSessionBindingEvent se) {

           }
       }
